<script lang="ts" setup>
import Codemirror from 'codemirror-editor-vue3'
import { ref } from 'vue'

const jsonInput = ref('')
const formattedJson = ref('')
const jsonTree = ref(null)
function formatJson() {
  try {
    const parsedJson = JSON.parse(jsonInput.value)
    formattedJson.value = JSON.stringify(parsedJson, null, 2)
    jsonTree.value = parsedJson
  }
  catch (error) {
    console.error(error)
    formattedJson.value = '无效的 JSON 字符串'
    jsonTree.value = null
  }
}
</script>

<template>
  <div class="json-parser-container">
    <div class="json-input-output">
      <div class="json-input">
        <Codemirror v-model:value="jsonInput" border placeholder="输入Json字符串" :height="400" @input="formatJson" />
      </div>
      <div class="json-output">
        <Codemirror v-model:value="formattedJson" border placeholder="显示格式化后的 JSON 字符串" :height="400" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.json-parser-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
}

.json-input-output {
  display: flex;
  flex: 1;
  gap: 20px;
  height: 500px;
  margin-bottom: 20px;
}

.json-input,
 .json-output {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.json-input textarea {
  flex: 1;
  padding: 10px;
  font-family: monospace;
  resize: none;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.json-output pre {
  flex: 1;
  padding: 10px;
  overflow: auto;
  background: #f5f5f5;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>
